﻿using System;
using System.Collections.Generic;
using System.Text;

namespace FreeSrun.Core
{
    public class PasswordEncryptor
    {
        public PasswordEncryptor() { }

        public string Encrypt(string password, long time)
        {
            string key = Math.Floor(time / 60.0).ToString(); //此处有修改，用原作者的算法无法登录
            return Encrypt(password, key);
        }

        private string Encrypt(string password, string key)
        {
            if (password.Length > 16)
            {
                password = password.Substring(0, 16);
            }
            int len = password.Length;
            string ret = "";
            for (int i = 0; i < len; i++)
            {
                int _pass = (int)password[i];
                int _key = GetKeychar(key, i);
                _key = _key ^ _pass;
                ret += BuildKey(_key, i % 2 == 1);
            }
            return ret;
        }

        private int GetKeychar(string str, int num)
        {
            int len = str.Length;
            return (int)str[len - num % len - 1];
        }

        private string BuildKey(int num, bool isReversed)
        {
            string ret = "";

            int low = num & 0x0f;
            int high = num >> 4;
            high = high & 0x0f;

            if (!isReversed)
            {
                ret += (char)(low + 0x36);
                ret += (char)(high + 0x63);
            }
            else
            {
                ret += (char)(high + 0x63);
                ret += (char)(low + 0x36);
            }
            return ret;
        }

    }
}
